package com.server.common.utils.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by draco on 14-4-23.
 */
@Component
public class OssService {
    private static final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    private static final String accessKeyId = "wBUBDY9KCquoXzgT";
    private static final String accessKeySecret = "9ihBrpRJ5NKJ7Nar7CDL26TS1FTnwb";
    private static final OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    private static final String bucketName = "resb";
    private static final String hostUrl = "http://res.daidai888.com/"; //让小金配置一下这个URL
    private static final Logger logger = Logger.getLogger(OssService.class);
    public void upload(File file){
        String fileName = UUID.randomUUID().toString().replace("-", "");
        client.putObject(new PutObjectRequest(bucketName, fileName, file));
    }
    public String upload(InputStream stream,String fileName){
        PutObjectResult putObjectResult = client.putObject(new PutObjectRequest(bucketName, fileName, stream));
        logger.info("etag:" + putObjectResult.getETag());
        return hostUrl+fileName;
    }
    public List<OssObject> getAllObject(){
        ObjectListing objectListing = client.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(1000));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        List<OssObject> ossObjects = new ArrayList<>();
        for (OSSObjectSummary s : sums) {
            OssObject ossObject = new OssObject();
            ossObject.seteTag(s.getETag());
            ossObject.setKey(s.getKey());
            ossObject.setLastModified(s.getLastModified());
            ossObject.setSize(s.getSize());
            ossObjects.add(ossObject);
        }
        return ossObjects;
    }

    public List<OssObject> getObject(String keyPrefix){
        ObjectListing objectListing = client.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(1000).withPrefix(keyPrefix));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        List<OssObject> ossObjects = new ArrayList<>();
        for (OSSObjectSummary s : sums) {
            OssObject ossObject = new OssObject();
            ossObject.seteTag(s.getETag());
            ossObject.setKey(s.getKey());
            ossObject.setLastModified(s.getLastModified());
            ossObject.setSize(s.getSize());
            ossObjects.add(ossObject);
        }
        return ossObjects;
    }
}